﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Serialization;
using System.IO.IsolatedStorage;
using System.IO;

namespace Tulde.WindowsPhone.Music
{
    public static class SettingsProvider
    {
        private static Settings _instance;
        private static string _fileName = "settings.app";
        public static Settings Settings
        {
            get
            {
                return _instance;
            }
        }
        public static void Load()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Settings));
            bool exists = false;
            //FileStream file = new FileStream(strPath, FileMode.OpenOrCreate);
           
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {

                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(_fileName, System.IO.FileMode.OpenOrCreate, isf))
                {
                    if (stream.Length > 0)
                    {
                        _instance = (Settings)serializer.Deserialize(stream);
                        exists = true;
                    }
                    
                }
            }

            if (!exists)
            {
                _instance = new Settings();
                Save();
            }
        }
        public static void Save()
        {
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                MemoryStream ms = new MemoryStream();
                XmlSerializer xs = new XmlSerializer(_instance.GetType());
                xs.Serialize(ms, _instance);

                ms.Seek(0, SeekOrigin.Begin);
                using (ms)
                {
                    IsolatedStorageFileStream file_stream = isf.CreateFile(_fileName);
                    if (file_stream == null) throw new Exception();
                    int READ_CHUNK = 1024 * 1024;
                    int WRITE_CHUNK = 1024 * 1024;
                    byte[] buffer = new byte[READ_CHUNK];
                    while (true)
                    {
                        int read = ms.Read(buffer, 0, READ_CHUNK);
                        if (read <= 0) break;
                        int to_write = read;
                        while (to_write > 0)
                        {
                            file_stream.Write(buffer, 0, Math.Min(to_write, WRITE_CHUNK));
                            to_write -= Math.Min(to_write, WRITE_CHUNK);
                        }
                    }

                    file_stream.Close();
                }

            }
        }
    }
}
